package dexter.util;

 public class ByteClassLoader extends ClassLoader {

   private String classname;
   private byte[] source;
   private ClassLoader parent;

   public ByteClassLoader (String name, byte[] bytes, ClassLoader contextLoader) {	   
     super();
     //System.out.println("ByteClassLoader : constructor "+bytes.length);  
     classname = name;
     source = bytes;
     parent = contextLoader;
     
   }
   
   public Class loadClass (String name, boolean resolve) throws ClassNotFoundException {
	   //System.out.println("ByteClassLoader : loadClass "+name+" <"+resolve+">");	
       if (name.equals(classname)) {
    	   byte[] b = loadClassData (name);
    	   //System.out.println("ByteClassLoader : reloading class : "+name);	
           Class c = defineClass (name, b, 0, b.length);
           return c;
       }
       else {
    	   return this.findClass (name);
       }
   }

   public Class findClass (String name) throws ClassNotFoundException {
	   //System.out.println("ByteClassLoader : findClass "+name);
   	   return parent.loadClass (name);
   }

   private byte[] loadClassData (String name) {
	 //System.out.println("ByteClassLoader : loadClassData "+name+" ("+source.length+" bs)");
     return source;
   }
   
//   public Class loadClass (String name, boolean resolve) throws ClassNotFoundException {
//	   System.out.println("ByteClassLoader : loadClass "+name+" <"+resolve+">");	
//
//    	   return this.findClass (name);
//
//   }
//
//   public Class findClass (String name) throws ClassNotFoundException {
//
//	   System.out.println("ByteClassLoader : findClass "+name);
//       byte[] b = loadClassData (name);
//       if (b.length>0) {
//    	   Class c = super.defineClass (name, b, 0, b.length);
//    	   return c;
//       }
//       else 
//    	   return parent.loadClass (name);
//   }
//
//
//   private byte[] loadClassData (String name) {
//	 System.out.println("ByteClassLoader : loadClassData "+name);
//     if (name.equals(classname)) return source;
//     return new byte[0];
//   }
}
